<script setup lang="ts">
import type { ILoginRequest } from '@fl/api/iam-api'
import type { FormInstance, FormRules } from 'element-plus'

import { usegetUserMenu, userCurrentUserInfo2, userLogin2 } from '@fl/api/iam-api'
import { SubmitBtn } from '@fl/components'
import { ElForm, ElFormItem } from 'element-plus'

const { push } = useRouter()

type IForm = Pick<ILoginRequest, 'password' | 'username'>

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive<IForm>({
    password: '',
    username: '',
})

const rules = reactive<FormRules<IForm>>({
    password: [
        {
            message: '请输入密码',
            required: true,
        },
    ],
    username: [
        {
            message: '请输入用户名',
            required: true,
        },
    ],
})

const { isPending: isPendingLogin, mutateAsync } = userLogin2()
const { isLoading: isLoadingUserInfo, refetch: refetchUserInfo } = userCurrentUserInfo2(false)
const { isLoading: isLoadingUserMenu, refetch: refetchUserMenu } = usegetUserMenu(false)

const isPending = computed(() => isPendingLogin.value || isLoadingUserInfo.value || isLoadingUserMenu.value) // 是否正在请求中

async function submitForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return

    const isValid = await formEl.validate()
    if (!isValid) {
        return false
    }

    const result = await mutateAsync(ruleForm)
    if (result) {
        await refetchUserInfo() // 缓存userInfo
        await refetchUserMenu() // 缓存菜单
        push('/')
    }
}
</script>

<template>
    <ElForm ref="ruleFormRef"
            label-position="top"
            :model="ruleForm"
            :rules="rules"
            @submit.prevent
    >
        <div class="mb-16 flex flex-col gap-12">
            <ElFormItem label="用户名"
                        prop="username"
            >
                <el-input v-model="ruleForm.username"
                          placeholder="请输入用户名"
                          maxlength="20"
                          size="large"
                />
            </ElFormItem>
        </div>

        <div class="flex flex-col gap-12">
            <ElFormItem label="密码"
                        prop="password"
            >
                <el-input v-model="ruleForm.password"
                          type="password"
                          show-password
                          maxlength="20"
                          placeholder="请输入密码"
                          size="large"
                />
            </ElFormItem>
        </div>

        <ElFormItem>
            <SubmitBtn type="primary"
                       native-type="submit"
                       class="mt-30 rounded-3 text-#fff lh-48 text-center w-full cursor-pointer"
                       size="large"
                       :loading="isPending"
                       @click="submitForm(ruleFormRef)"
            >
                登录
            </SubmitBtn>
        </ElFormItem>
    </ElForm>
</template>
